﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace DataInspector
{
    public static class DIUtils
    {
        public static void CopyStream(Stream input, Stream output, long length, DataInspector.ProgressCallback callback)
        {
            long totalsize = input.Length;
            long byteswritten = 0;
            const int size = 32768;
            byte[] buffer = new byte[size];
            int read;
            int readlen = length < size ? (int)length : size;
            while (length > 0 && (read = input.Read(buffer, 0, readlen)) > 0)
            {
                output.Write(buffer, 0, read);
                byteswritten += read;
                length -= read;
                readlen = length < size ? (int)length : size;
                if (callback != null)
                    callback(byteswritten, totalsize);
            }
        }

        public static void SaveToFile(Stream stream, string outputFile, DataInspector.ProgressCallback progressCallback)
        {
            Stream inputStream = stream;

            inputStream.Position = 0;

            using (var outputStream = File.OpenWrite(outputFile))
            {
                const int bufferSize = 4096;
                while (inputStream.Position < inputStream.Length)
                {
                    byte[] data = new byte[bufferSize];
                    int amountRead = inputStream.Read(data, 0, bufferSize);
                    outputStream.Write(data, 0, amountRead);

                    if (progressCallback != null)
                        progressCallback(inputStream.Position, inputStream.Length);
                }
                outputStream.Flush();
            }
        }
    }
}
